package com.map.event;


import android.annotation.SuppressLint;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import com.map.core.MapView;

import java.util.ArrayList;
import java.util.List;

public class MapListener implements View.OnTouchListener {

    private int pointerCount;//触控点数量
    private final MapView mapView;
    private final static String TAG = "地图事件";

    private List<ZoomListener> zoomListeners;//平移监听任务集

    private float X, Y;//上次坐标

    public MapListener(MapView mapView) {
        this.mapView = mapView;
        zoomListeners = new ArrayList<>();
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        if (motionEvent != null) {
            pointerCount = motionEvent.getPointerCount();
            final float normalizedX =
                    (motionEvent.getX() / (float) view.getWidth()) * 2 - 1;
            final float normalizedY =
                    -((motionEvent.getY() / (float) view.getHeight()) * 2 - 1);
            switch (motionEvent.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    Log.e(TAG, "点击事件");

                    X = normalizedX;
                    Y = normalizedY;
                    break;
                case MotionEvent.ACTION_MOVE:
                    Log.e(TAG, "移动事件");

                    move(normalizedX - X, normalizedY - Y);
                    X = normalizedX;
                    Y = normalizedY;
                    break;
                case MotionEvent.ACTION_UP:
                    Log.e(TAG, "抬起事件");
                    break;
                case MotionEvent.ACTION_SCROLL:
                    Log.e(TAG, "滚动事件");
                    break;
                default:
                    break;
            }
            return true;
        } else {
            return false;
        }

    }

    /**
     * 地图平移事件
     *
     * @param dx OpenGL坐标系x增量
     * @param dy OpenGL坐标系y增量
     */
    public void move(final float dx, final float dy) {
        mapView.queueEvent(new Runnable() {
            @Override
            public void run() {
                mapView.getRender().move(dx, dy);
            }
        });
        mapView.refresh();
    }

    /**
     * 点击事件
     *
     * @param x OpenGL绘图坐标系x
     * @param y OpenGL绘图坐标系y
     */
    public void click(float x, float y) {

    }

    /**
     * 地图缩放监听
     *
     * @param level 新的地图等级
     */
    public void onZoom(int level) {
        //执行已有移动监听
        for (int i = 0; i < zoomListeners.size(); i++) {
            ZoomListener zoomListener = zoomListeners.get(i);
            zoomListener.zoom(level);
        }
    }
}
